
const CAR = "car"
const GOAT = "goat"

let outputEl = document.getElementById('output');
let scene = [];
let countOfSimulation = 50000;

let countOfWin = 0, countOfLost = 0;
let countOfWinIfExchange = 0, countOfLostIfExchange = 0;

function init() {
    let whereIsTheCar = Math.floor(Math.random() * 3);
    console.log(`Car is behand the No.${whereIsTheCar + 1} door`)
    for (let index = 0; index < 3; index++) {
        scene[index] = whereIsTheCar == index ? CAR : GOAT;
    }
    outputEl.innerHTML += scene.join(' ');
}

function choose() {
    let whichDoorIChoosing = Math.floor(Math.random() * 3);

    // not exchange
    let win = judgeWin(whichDoorIChoosing)
    if (win) {
        countOfWin++
    } else {
        countOfLost++
    }

    // if i exchange
    let whichDoorIfExchange = exchangeTo(whichDoorIChoosing);
    let winIfExchange = judgeWin(whichDoorIfExchange);
    if (winIfExchange) {
        countOfWinIfExchange++
    } else {
        countOfLostIfExchange++
    }

    console.log(`I choosing the No.${whichDoorIChoosing + 1} door, If i exchange it'll be No.${1 + whichDoorIfExchange}`)
    outputEl.innerHTML += "==== I choosing " + scene[whichDoorIChoosing]
        + " Result: " + win ? 'Win' : 'Lost' + "<br />";
}

function exchangeTo(choosing) {
    let doorNo = [0, 1, 2];
    let doorToExchange = null;
    if (judgeWin(choosing)) {
        doorToExchange = doorNo.join(',').replace(new RegExp("^" + choosing + ",|," + choosing), '').split(',')[Math.floor(Math.random() * 2)];
    } else {
        doorToExchange = scene.indexOf(CAR);
    }
    return doorToExchange;
}

function judgeWin(choosing) {
    return scene[choosing] == CAR
}

function simulate() {
    for (let index = 0; index < countOfSimulation; index++) {
        init();
        choose();
    }
    console.log(`Simulated:${countOfSimulation} times\n No exchange:: Win:${countOfWin}, Lost:${countOfLost}, Probability:${countOfWin / countOfSimulation * 100}% \n If exchange:: Win:${countOfWinIfExchange}, Lost:${countOfLostIfExchange}, Probability:${countOfWinIfExchange / countOfSimulation * 100}%`)
}

simulate();